//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.eshop.modules.mp.listener;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.eshop.enums.BillDetailEnum;
import com.eshop.enums.PayTypeEnum;
import com.eshop.event.TemplateBean;
import com.eshop.event.TemplateEvent;
import com.eshop.event.TemplateListenEnum;
import com.eshop.modules.activity.domain.UserExtract;
import com.eshop.modules.activity.service.UserExtractService;
import com.eshop.modules.customer.domain.StoreCustomer;
import com.eshop.modules.customer.service.StoreCustomerService;
import com.eshop.modules.mp.service.WeiXinSubscribeService;
import com.eshop.modules.mp.service.WeixinPayService;
import com.eshop.modules.mp.service.WeixinTemplateService;
import com.eshop.modules.user.domain.ShopUser;
import com.eshop.modules.user.service.UserBillService;
import com.eshop.modules.user.service.UserService;
import com.eshop.modules.user.service.dto.WechatUserDto;
import com.github.binarywang.wxpay.exception.WxPayException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class TemplateListener implements SmartApplicationListener {
    private static final Logger log = LoggerFactory.getLogger(TemplateListener.class);
    @Autowired
    private UserService userService;
    @Autowired
    private WeixinTemplateService weixinTemplateService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private WeiXinSubscribeService weiXinSubscribeService;
    @Autowired
    private UserExtractService userExtractService;
    @Autowired
    private WeixinPayService payService;
    @Autowired
    private UserBillService billService;
    @Autowired
    private StoreCustomerService storeCustomerService;

    public TemplateListener() {
    }

    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == TemplateEvent.class;
    }

    @Async
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        TemplateEvent templateEvent = (TemplateEvent)applicationEvent;
        TemplateBean templateBean = templateEvent.getTemplateBean();
        log.info("模板事件类型：{}", templateBean.getTemplateType());
        switch(TemplateListenEnum.toType(templateBean.getTemplateType())) {
            case TYPE_1:
                this.weixinTemplateService.paySuccessNotice(templateBean.getOrderId(), templateBean.getPrice(), templateBean.getUid());
                this.weiXinSubscribeService.paySuccessNotice(templateBean.getOrderId(), templateBean.getPrice(), templateBean.getUid());

                try {
                    List<StoreCustomer> storeCustomers = (this.storeCustomerService.lambdaQuery().eq(StoreCustomer::getIsEnable, 1)).list();
                    storeCustomers.forEach((msg) -> {
                        if (StrUtil.isNotBlank(msg.getOpenId())) {
                            this.weixinTemplateService.paySuccessNoticeToKefu(templateBean.getOrderId(), templateBean.getPrice(), msg.getOpenId());
                        }

                    });
                } catch (Exception var12) {
                    log.error("消息发送失败:{}", var12);
                }
                break;
            case TYPE_2:
                if (PayTypeEnum.WEIXIN.getValue().equals(templateBean.getPayType())) {
                    BigDecimal bigDecimal = new BigDecimal("100");
                    int payPrice = bigDecimal.multiply(new BigDecimal(templateBean.getPrice())).intValue();
                    this.weixinPayService.refundOrder(templateBean.getOrderId(), payPrice);
                }

                this.weixinTemplateService.refundSuccessNotice("您的订单退款申请被通过，钱款将很快还至您的支付账户。", templateBean.getOrderId(), templateBean.getPrice(), templateBean.getUid(), templateBean.getTime());
                break;
            case TYPE_3:
                this.weixinTemplateService.deliverySuccessNotice(templateBean.getOrderId(), templateBean.getDeliveryName(), templateBean.getDeliveryId(), templateBean.getUid());
                break;
            case TYPE_4:
                this.weixinTemplateService.rechargeSuccessNotice(templateBean.getTime(), templateBean.getPrice(), templateBean.getUid());
                break;
            case TYPE_7:
                log.info("投递延时订单id： [{}]：", templateBean.getOrderId());
                break;
            case TYPE_8:
                UserExtract resources = (UserExtract)this.userExtractService.getById(templateBean.getExtractId());
                Boolean success = false;
                ShopUser user = (ShopUser)this.userService.getById(resources.getUid());
                if (user != null) {
                    WechatUserDto wechatUser = user.getWxProfile();
                    if (ObjectUtil.isNotNull(wechatUser) && ObjectUtil.isNotNull(wechatUser.getRoutineOpenid())) {
                        try {
                            String nonce_str = UUID.randomUUID().toString().replace("-", "");
                            this.payService.entPay(wechatUser.getRoutineOpenid(), nonce_str, resources.getRealName(), resources.getExtractPrice().multiply(new BigDecimal(100)).intValue());
                            success = true;
                        } catch (WxPayException var11) {
                            log.error("退款失败,原因:{}", var11.getMessage());
                        }
                    }
                }

                if (!success) {
                    String mark = "提现失败,退回佣金" + resources.getExtractPrice() + "元";
                    double balance = NumberUtil.add(user.getBrokeragePrice(), resources.getExtractPrice()).doubleValue();
                    this.billService.income(resources.getUid(), "提现失败", BillDetailEnum.CATEGORY_1.getValue(), BillDetailEnum.TYPE_4.getValue(), resources.getExtractPrice().doubleValue(), balance, mark, resources.getId().toString());
                    this.userService.incBrokeragePrice(resources.getExtractPrice(), resources.getUid());
                    resources.setFailTime(new Date());
                    this.userExtractService.updateById(resources);
                }
                break;
            case TYPE_9:
                this.weixinTemplateService.refundSuccessNotice("您的订单退款申请已提交,等待审核。", templateBean.getOrderId(), templateBean.getPrice(), templateBean.getUid(), templateBean.getTime());

                try {
                    List<StoreCustomer> storeCustomers = ((LambdaQueryChainWrapper)this.storeCustomerService.lambdaQuery().eq(StoreCustomer::getIsEnable, 1)).list();
                    storeCustomers.forEach((msg) -> {
                        if (StrUtil.isNotBlank(msg.getOpenId())) {
                            this.weixinTemplateService.refundSuccessNoticeToKefu("尊敬的客服,您有新的退款申请待处理!", templateBean.getOrderId(), templateBean.getPrice(), msg.getOpenId(), templateBean.getTime());
                        }

                    });
                } catch (Exception var10) {
                    log.error("消息发送失败:{}", var10);
                }
        }

    }
}
